<?php

namespace appApi\components;



class ApiParameters
{
    /**
     * @var string 访问所需的令牌, 参数名 access_token
     */
    public $accessToken;
    /**
     * @var string 登录后用户的授权访问令牌,参数名 user_token
     */
    public $userToken;
    /**
     * @var int 发起请求时的时间戳,参数名 timestamp
     */
    public $timestamp;
    /**
     * @var string 请求附带的随机字符串,保证每次请求都不一样,参数名 once
     */
    public $once;
    /**
     * @var string 请求附带参数,API服务端不做任何处理,原值返回,参数名 attach
     */
    public $attach = '';
    /**
     * @var string 请求数据格式和返回数据格式,默认为JSON,可选择: JSON/XML/JSONP,参数名 format
     */
    public $format;
    /**
     * @var string 签名方法,默认MD5,参数名 sign_type
     */
    public $signType;
    /**
     * @var string 签名字符串,参数名 sign
     */
    public $sign;
    /**
     * @var string 请求的接口的版本, 参数名 version
     */
    public $version;
    /**
     * @var string 请求接口的具体处理方法,参数名 method
     */
    public $method;
    /**
     * @var string 请求的业务数据,参数名 data
     */
    public $data;

    /**
     * ApiParameters constructor.
     * @param \yii\web\Request|\yii\console\Request $req
     */
    public function __construct($req)
    {
        $this->accessToken = $req->post('access_token');
        $this->userToken = $req->post('user_token');
        $this->timestamp = $req->post('timestamp');
        $this->once = $req->post('once');
        $this->attach = $req->post('attach');
        $this->format = $req->post('format');
        $this->sign_type = $req->post('sign_type');
        $this->sign = $req->post('sign');
        $this->version = $req->post('version');
        $this->method = $req->post('method');
        $this->data = $req->post('data');
    }

    /**
     * 请求的JSON格式字符串
     * @return string
     */
    public function toJson()
    {
        return json_encode([
            'get' => $_GET,
            'post_body' => $this->getUrlParams()
        ]);
    }

    /**
     * 获取请求的有效参数数组
     * @return array
     */
    public function getUrlParams()
    {
        return [
            'access_token' => $this->accessToken,
            'user_token' => $this->userToken,
            'timestamp' => $this->timestamp,
            'once' => $this->once,
            'attach' => $this->attach,
            'format' => $this->format,
            'sign_type' => $this->signType,
            'sign' => $this->sign,
            'version' => $this->version,
            'method' => $this->method,
            'data' => $this->data,
        ];
    }
}